<!-- 单坐席预测 -->
<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="5">
					<a-form-item label="创建人姓名" name="createUser">
						<UserSelect v-model:value="searchFormState.createUser" />
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="所属公司" name="createDept">
						<a-tree-select
							v-model:value="searchFormState.createDept"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择组织"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:tree-default-expanded-keys="treeDefaultExpandedKeys"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="批次状态" name="batchStatus">
						<a-select
							v-model:value="searchFormState.batchStatus"
							placeholder="请选择批次状态"
							:options="preOutCallBatchStatusOptions"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="日期范围">
						<a-range-picker v-model:value="dateRange" valueFormat="YYYY-MM-DD" :allowClear="false" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-space>
						<a-button type="primary" @click="pageList(1)">查询</a-button>
						<a-button class="ml-3" @click="reset">重置</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false" class="mt-2">
		<div class="opration">
			<div class="Btn">
				<a-button type="primary" @click="formRef.onOpen('MEDIATOR_IMPORT', props.callType)">
					<UploadOutlined />
					坐席导入
				</a-button>
				<a-button class="m-l-24" type="primary" @click="formRef.onOpen('ADMIN_IMPORT', props.callType)">
					<UploadOutlined />
					主管导入
				</a-button>
			</div>
			<div class="custom m-l-24">
				<span>自定义展示信息：{{ htWebCall.customerInfo }}</span>
			</div>
			<a-checkbox v-model:checked="isShowSelf" @change="onModelUpdate">只看自己</a-checkbox>
		</div>
		<a-table
			ref="tableRef"
			:columns="columns"
			:data-source="preOutList"
			bordered
			size="middle"
			:row-key="(record) => record.id"
			:scroll="{ x: 'max-content' }"
			:pagination="pagination"
			@change="handleTableChange"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a-button
							v-if="record.batchStatus === 0"
							type="link"
							size="small"
							:disabled="record.startDisabled"
							@click="startTask(record)"
							>开始
						</a-button>
						<a-button type="link" size="small" @click="copyFormRef.onOpen(record)"> 复制 </a-button>
						<a-button v-if="record.batchStatus === 1" type="link" size="small" @click="pauseTask(record.batchNumber)"
							>暂停
						</a-button>
						<a-button
							v-if="record.batchStatus === 2"
							type="link"
							size="small"
							:disabled="record.continueDisabled"
							@click="continueTask(record)"
							>继续
						</a-button>
						<a-popconfirm
							v-if="record.batchStatus === 1 || record.batchStatus === 2"
							title="确定要作废吗？"
							@confirm="finishTask(record.batchNumber)"
						>
							<a-button type="link" size="small">作废</a-button>
						</a-popconfirm>
						<a-popconfirm
							v-if="record.batchStatus === 0 || record.batchStatus === 4"
							title="确定要删除吗？"
							@confirm="delPredictCall(record.batchNumber)"
						>
							<a-button type="link" size="small">删除</a-button>
						</a-popconfirm>
						<a-button type="link" size="small" @click="detailRef.onOpen(record)">详情</a-button>
					</a-space>
				</template>
			</template>
		</a-table>
	</a-card>
	<Upload ref="formRef" @successful="pageList(pagination.current)" />
	<CopyForm ref="copyFormRef" @successful="pageList(pagination.current)" />
	<Detail ref="detailRef" />
</template>

<script setup name="">
	import tool from '@/utils/tool'
	import UserSelect from '@/components/XnUserSelector/userSelect.vue'
	import dayjs from 'dayjs'
	import Upload from '@/views/tjzy/call/predict/upload.vue'
	import htWebCall from '@/plugins/htWebCall'
	import bizUserApi from '@/api/biz/bizUserApi'
	import predictCallApi from '@/api/tjzy/call/predict/predictCallApi'
	import CopyForm from '@/views/tjzy/call/predict/copyForm.vue'
	import Detail from '@/views/tjzy/call/predict/detail.vue'

	const props = defineProps({
		callType: Number
	})
	const pagination = ref({
		current: 1, // 当前页码
		pageSize: 10, // 每页条数
		total: 0, // 数据总量
		showSizeChanger: true, // 是否可以改变每页数量
		pageSizeOptions: ['10', '20', '50', '100'],
		showQuickJumper: true,
		showTotal: (total, range) => {
			return `${range[0]}-${range[1]} 共 ${total} 条 `
		}
	})

	const searchFormState = ref({
		current: pagination.value.current,
		size: pagination.value.pageSize,
		callType: props.callType,
		createUserName: undefined,
		createDept: undefined,
		batchStatus: undefined,
		taskId: undefined
	})
	let intervalTimer = null //定时器
	const preOutCallBatchStatusOptions = tool.dictList('PreOutCallBatchStatus')
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	const copyFormRef = ref()
	const detailRef = ref()
	const preOutList = ref([])
	const treeData = ref([])
	const treeDefaultExpandedKeys = ref([])
	const isShowSelf = ref(false)
	const columns = [
		{
			title: '批次号',
			dataIndex: 'batchNumber'
		},
		{
			title: '任务名称',
			dataIndex: 'batchName'
		},
		{
			title: '批次状态',
			dataIndex: 'batchStatusName'
		},
		{
			title: '主叫号码',
			dataIndex: 'caller',
			ellipsis: true
		},
		{
			title: '号码名称',
			dataIndex: 'callName',
			ellipsis: true
		},
		{
			title: '总数',
			dataIndex: 'totalCount'
		},
		{
			title: '已完成数量',
			dataIndex: 'completedCount',
			ellipsis: true
		},
		{
			title: '创建人',
			dataIndex: 'createUserName'
		},
		{
			title: '创建时间',
			dataIndex: 'createTime'
		},
		{
			title: '最后更新时间',
			dataIndex: 'updateTime'
		},
		{
			title: '操作',
			dataIndex: 'action',
			fixed: 'right',
			align: 'center'
		}
	]
	let dateRange = ref([
		dayjs().subtract(7, 'day').format('YYYY-MM-DD'), // 今天减去三天
		dayjs().format('YYYY-MM-DD') // 今天的日期
	]) //日期范围

	const onModelUpdate = (event) => {
		if (event.target.checked) {
			searchFormState.value.createUser = tool.data.get('USER_INFO').id
		} else {
			searchFormState.value.createUser = undefined
		}
		pageList(pagination.value.current)
	}

	const pageList = (current) => {
		searchFormState.value.current = current
		searchFormState.value.beginTime = `${dateRange.value[0]} 00:00:00`
		searchFormState.value.endTime = `${dateRange.value[1]} 23:59:59`
		predictCallApi.pageList(searchFormState.value).then((res) => {
			preOutList.value = res.records
			pagination.value.total = res.total
			pagination.value.current = res.current
			pagination.value.pageSize = res.size
		})
	}

	const reset = () => {
		searchFormRef.value.resetFields()
		dateRange.value = [
			dayjs().subtract(6, 'day').format('YYYY-MM-DD'), // 今天减去7天
			dayjs().format('YYYY-MM-DD') // 今天的日期
		]
		pageList(1)
	}

	const handleTableChange = (pagination) => {
		if (!(searchFormState.value.current === pagination.current && searchFormState.value.size === pagination.pageSize)) {
			searchFormState.value.size = pagination.pageSize
			pageList(pagination.current)
		}
	}

	const startTask = (record) => {
		record.startDisabled = true
		predictCallApi.startCallTask(record.batchNumber).then(() => {
			pageList(pagination.value.current)
		})
		setTimeout(() => {
			record.startDisabled = false
		}, 3000)
	}

	const pauseTask = (batchNumber) => {
		predictCallApi.pauseCallTask(batchNumber).then(() => {
			pageList(pagination.value.current)
		})
	}
	const continueTask = (record) => {
		record.continueDisabled = true
		predictCallApi.continueCallTask(record.batchNumber).then(() => {
			pageList(pagination.value.current)
		})
		setTimeout(() => {
			record.continueDisabled = false
		}, 3000)
	}
	const finishTask = (batchNumber) => {
		predictCallApi.finishCallTask(batchNumber).then(() => {
			pageList(pagination.value.current)
		})
	}
	const delPredictCall = (batchNumber) => {
		predictCallApi.delPredictCall(batchNumber).then(() => {
			pageList(pagination.value.current)
		})
	}
	onMounted(() => {
		intervalTimer = setInterval(() => {
			pageList(pagination.value.current)
		}, 10000)

		pageList(1)
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				treeData.value = res
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								treeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		})
	})
	onUnmounted(() => {
		//清除定时器
		if (intervalTimer) {
			clearInterval(intervalTimer)
			intervalTimer = null
		}
	})
</script>
<style scoped>
	.opration {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 1.25rem;
	}

	.custom {
		flex: auto;
	}
</style>
